package org.xxpay.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.xxpay.core.common.util.MyLog;
import org.xxpay.core.entity.*;
import org.xxpay.core.service.IPayInterfaceTypeTemplateService;
import org.xxpay.service.dao.mapper.*;

import java.util.List;

/**
 * @author: xiaoyu
 * @date: 2019/6/20
 * @description: 支付接口类型参数模板表
 */
@Service
public class PayInterfaceTypeTemplateServiceImpl implements IPayInterfaceTypeTemplateService {

    @Autowired
    private PayInterfaceTypeTemplateMapper payInterfaceTypeTemplateMapper;

    @Autowired
    private PayPassageAccountMapper payPassageAccountMapper;

    @Autowired
    private AlipayCashMapper alipayCashMapper;

    @Autowired
    private AlipayCashDetailMapper alipayCashDetailMapper;

    @Autowired
    private PayAlizftMchInfoMapper payAlizftMchInfoMapper;

    private MyLog _log = MyLog.getLog(PayInterfaceTypeTemplateServiceImpl.class);

    @Override
    public int add(PayInterfaceTypeTemplate payInterfaceTypeTemplate) {
        return payInterfaceTypeTemplateMapper.insertSelective(payInterfaceTypeTemplate);
    }

    @Override
    public int update(PayInterfaceTypeTemplate payInterfaceTypeTemplate) {
        int updateRow = payInterfaceTypeTemplateMapper.updateByPrimaryKeySelective(payInterfaceTypeTemplate);

        // mchId 或者 params为空，则不更新子账号冗余字段（状态变更按钮触发时）
        if (StringUtils.isAnyEmpty(payInterfaceTypeTemplate.getPassageMchIdTemplate(), payInterfaceTypeTemplate.getParamTemplate())) {
            return updateRow;
        }

        // 如果为支付通直付通，更新二级商户的结算方式
        // TODO 代码耦合了，需要再优化
        if(payInterfaceTypeTemplate.getIfTypeCode().equals("alizftpay")) {
            try {
                String paramTemplate = payInterfaceTypeTemplate.getParamTemplate();
                JSONObject jsonObject = JSONObject.parseObject(paramTemplate);
                Byte settType = jsonObject.getByte("settType");
                PayAlizftMchInfo updatePayAlizftMchInfo = new PayAlizftMchInfo();
                updatePayAlizftMchInfo.setSettType(settType);
                PayAlizftMchInfoExample payAlizftMchInfoExample = new PayAlizftMchInfoExample();
                payAlizftMchInfoExample.createCriteria().andPassageTemplateIdEqualTo(payInterfaceTypeTemplate.getId());
                payAlizftMchInfoMapper.updateByExampleSelective(updatePayAlizftMchInfo, payAlizftMchInfoExample);
            }catch (Exception e) {
                _log.error(e, "");
            }
        }

        //更新所有引用子账号， 改为模板内容
        PayPassageAccount updateRecord = new PayPassageAccount(); //更新内容
        updateRecord.setParam(payInterfaceTypeTemplate.getParamTemplate());
        updateRecord.setPassageMchId(payInterfaceTypeTemplate.getPassageMchIdTemplate());

        PayPassageAccountExample condition = new PayPassageAccountExample(); //更新条件
        condition.createCriteria().andTemplateIdEqualTo(payInterfaceTypeTemplate.getId());
        updateRow  += payPassageAccountMapper.updateByExampleSelective(updateRecord, condition);
        return updateRow;
    }

    @Override
    public PayInterfaceTypeTemplate findById(Long id) {
        return payInterfaceTypeTemplateMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<PayInterfaceTypeTemplate> select(int offset, int limit, PayInterfaceTypeTemplate payInterfaceTypeTemplate) {
        PayInterfaceTypeTemplateExample example = new PayInterfaceTypeTemplateExample();
        example.setOrderByClause("createTime DESC");
        example.setOffset(offset);
        example.setLimit(limit);
        PayInterfaceTypeTemplateExample.Criteria criteria = example.createCriteria();
        setCriteria(criteria, payInterfaceTypeTemplate);
        return payInterfaceTypeTemplateMapper.selectByExample(example);
    }

    @Override
    public Integer count(PayInterfaceTypeTemplate payInterfaceTypeTemplate) {
        PayInterfaceTypeTemplateExample example = new PayInterfaceTypeTemplateExample();
        PayInterfaceTypeTemplateExample.Criteria criteria = example.createCriteria();
        setCriteria(criteria, payInterfaceTypeTemplate);
        return payInterfaceTypeTemplateMapper.countByExample(example);
    }

    @Override
    public List<PayInterfaceTypeTemplate> selectAll(PayInterfaceTypeTemplate payInterfaceTypeTemplate) {
        PayInterfaceTypeTemplateExample example = new PayInterfaceTypeTemplateExample();
        example.setOrderByClause("createTime DESC");
        PayInterfaceTypeTemplateExample.Criteria criteria = example.createCriteria();
        setCriteria(criteria, payInterfaceTypeTemplate);
        return payInterfaceTypeTemplateMapper.selectByExample(example);
    }

    @Override
    @Transactional(transactionManager = "transactionManager", rollbackFor = Exception.class)
    public int relationDelete(List<Long> ids, boolean isDeleteAlipayCash){

        int result = 0;

        //删除 使用该模板的子账号表
        PayPassageAccountExample accountExa = new PayPassageAccountExample();
        accountExa.createCriteria().andTemplateIdIn(ids);
        result += payPassageAccountMapper.deleteByExample(accountExa);

        //删除模板记录
        PayInterfaceTypeTemplateExample templateExa = new PayInterfaceTypeTemplateExample();
        templateExa.createCriteria().andIdIn(ids);
        result += payInterfaceTypeTemplateMapper.deleteByExample(templateExa);

        if(isDeleteAlipayCash){ //是否删除对应红包

            List<Integer> cashIds = alipayCashMapper.selectAllIdByTemplateAccountIds(ids); //查询出所有的红包记录
            if(!cashIds.isEmpty()){
                //删除红包明细记录
                AlipayCashDetailExample alipayCashDetailExample = new AlipayCashDetailExample();
                alipayCashDetailExample.createCriteria().andCashIdIn(cashIds);
                result += alipayCashDetailMapper.deleteByExample(alipayCashDetailExample);

                //删除红包记录主表
                AlipayCashExample alipayCashExample = new AlipayCashExample();
                alipayCashExample.createCriteria().andIdIn(cashIds);
                result += alipayCashMapper.deleteByExample(alipayCashExample);
            }
        }
        return result;
    }

    void setCriteria(PayInterfaceTypeTemplateExample.Criteria criteria, PayInterfaceTypeTemplate obj) {
        if(obj != null) {
            if(obj.getIfTypeCode() != null) criteria.andIfTypeCodeEqualTo(obj.getIfTypeCode());
            if(obj.getBelongInfoId() != null) criteria.andBelongInfoIdEqualTo(obj.getBelongInfoId());
            if(obj.getBelongInfoType() != null) criteria.andBelongInfoTypeEqualTo(obj.getBelongInfoType());
            if(obj.getStatus() != null && obj.getStatus().byteValue() != -99) criteria.andStatusEqualTo(obj.getStatus());
            if(StringUtils.isNotEmpty(obj.getPsStringVal("belongInfoTypeIn"))){
                JSONArray array = JSONArray.parseArray(obj.getPsStringVal("belongInfoTypeIn"));
                criteria.andBelongInfoTypeIn(array.toJavaList(Byte.class));
            }
        }
    }
}
